package com.linkhub.oms.component.mp.enums;

import com.linkhub.oms.common.exception.BizException;
import com.linkhub.oms.component.mp.util.QtMpUpdateAssist;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description: MpUpdateTypeEnum
 * @Author: echo
 * @Date: 2024/05/18 16:17
 * @Version: 1.0
 */
@AllArgsConstructor
@Getter
public enum MpUpdateTypeEnum {

    BIG_DECIMAL(1, BigDecimal.class, QtMpUpdateAssist.INDICATE_NULL_NUMBER),
    LOCAL_DATE_TIME(2, LocalDateTime.class, QtMpUpdateAssist.INDICATE_NULL_DATE_TIME),
    LOCAL_DATE(3, LocalDate.class, QtMpUpdateAssist.INDICATE_NULL_DATE),
    LONG(4, Long.class, QtMpUpdateAssist.INDICATE_NULL_LONG),
    INTEGER(5, Integer.class, QtMpUpdateAssist.INDICATE_NULL_INTEGER)
    ;

    private final Integer type;
    private final Class<?> clazz;
    private final Object indicateNullValue;

    static {
        // 校验字段类型是否对应
        Arrays.stream(values())
                .forEach(e -> {
                    if (!Objects.equals(e.getClazz(), e.getIndicateNullValue().getClass())) {
                        throw new BizException(String.format("【%s】MP更新字段类型与表示为null的值类型不一致", e));
                    }
                });
    }

    public static MpUpdateTypeEnum acquireByClass(Class<?> clazz) {
        return Arrays.stream(values())
                .filter(e -> clazz.equals(e.getClazz()))
                .findFirst()
                .orElse(null);
    }

    public static <T> T acquireNullValue(Class<T> clazz) {
        return Optional.ofNullable(acquireByClass(clazz))
                .map(MpUpdateTypeEnum::getIndicateNullValue)
                .map(val -> (T) val)
                .orElse(null);
    }
}
